<template>
  <div class="hwx-role-permissions">
    <Vmask
      :maskTitle="maskTitle"
      :maskData="maskData"
      :showMask="showMask"
      :maskWidth="maskWidth"
      @FnMask="FnMask"
    ></Vmask>
    <h3 class="lh40">角色权限</h3>
    <div class="role-permissions-content clearfix bgc-fff">
      <div class="role-permissions-content-left fl">
        <div class="lh40 centent pointer">
          <el-row>
            <el-col :span="8">
              <div
                class="grid-content bg-purple-dark default-color"
                @click="FnRoleEvent({type:'addRole'})"
              >新增</div>
            </el-col>
            <el-col :span="8">
              <div
                class="grid-content bg-purple-dark default-color"
                @click="FnRoleEvent({type:'editRole'})"
              >编辑</div>
            </el-col>
            <el-col :span="8">
              <div
                class="grid-content bg-purple-dark default-color"
                @click="FnRoleEvent({type:'deleteRole'})"
              >删除</div>
            </el-col>
          </el-row>
        </div>
        <div class="role-permissions-content-left-table">
          <ShowTable
            :tableData="tableData"
            :selections="selections"
            :lableList="lableList"
            :talLength="talLength"
            :pageSize="pageSize"
            :pageNum="pageNum"
            @getSortableFn="getSortableFn"
          ></ShowTable>
        </div>
      </div>
      <div class="role-permissions-content-right" v-if="showPermissionsDetails">
        <!-- <PermissionsDetails :getPermissionsDetailsDate='getPermissionsDetailsDate' @FnDetails="FnDetails"></PermissionsDetails> -->
        <div class="hsx-permissions-details">
          <!-- 角色权限详情 -->
          <div class="row condition clearfix lh40 oh">
            <div class="row-item clearfix fl mr15 mb15">
              <span class="row-item-title fl">角色名称：</span>
              <span class="fl span-input">
                <el-input placeholder="请输入内容" v-model.trim="rolePermissionsData.roleName"></el-input>
              </span>
            </div>
            <div class="row-item clearfix fl mr15 mb15">
              <span class="row-item-title fl">角色编码：</span>
              <span class="fl span-input">
                <el-input placeholder="请输入内容" v-model.trim="rolePermissionsData.roleCode"></el-input>
              </span>
            </div>
            <div class="row-item clearfix fl mb15" v-if="rolePermissionsData.isEdit">
              <el-button type="primary" @click="FnRolePermissionModify">修改</el-button>
            </div>
            <div class="row-item clearfix fl mb15" v-else>
              <el-button type="primary" @click="FnSave">保存</el-button>
            </div>
          </div>
          <div class="h-permissions-details-tabs">
            <el-tabs v-model="activeName" @tab-click="handleClick">
              <el-tab-pane label="角色权限" name="first">
                <div class="permissions-select">
                  <table cellspacing="0" cellpadding="0">
                    <thead>
                      <!-- <th>序号</th> -->
                      <th>菜单名称</th>
                      <th>全选</th>
                      <th>权限名称</th>
                    </thead>
                    <tbody>
                      <tr v-for="item in permissionsSelectionList">
                        <!-- <td>{{item.id}}</td> -->
                        <td>{{item.title}}</td>
                        <td>
                          <el-checkbox
                            v-model="item.all"
                            @change="FnPermissionsSelectionAll(item,item.all)"
                          ></el-checkbox>
                        </td>
                        <td>
                          <el-checkbox-group
                            v-model="item.model"
                            @change="FnPermissionsSelection(item.model,item)"
                          >
                            <el-checkbox v-for="i in item.list" :label="i.label + '@@' + i.value" :key="i.value">{{i.label}}</el-checkbox>
                          </el-checkbox-group>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
                <br>
                <div class="permissions-select" v-if="showSelectSecondaryListBox">
                  <table cellspacing="0" cellpadding="0">
                    <thead>
                      <!-- <th>序号</th> -->
                      <th>菜单名称</th>
                      <th>全选</th>
                      <th>权限名称</th>
                    </thead>
                    <tbody>
                      <tr v-for="item in selectSecondaryList">
                        <!-- <td>{{item.id}}</td> -->
                        <td>{{item.title}}</td>
                        <td>
                          <el-checkbox
                            v-model="item.all"
                            @change="FnSelectSecondaryAll(item,item.all)"
                          ></el-checkbox>
                        </td>
                        <td>
                          <el-checkbox-group
                            v-model="item.model"
                            @change="FnSelectSecondary(item.model,item)"
                          >
                            <el-checkbox v-for="i in item.list" :label="i.label + '@@' + i.value" :key="i.value">{{i.label}}</el-checkbox>
                          </el-checkbox-group>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </el-tab-pane>
              <el-tab-pane label="包含用户" name="second" v-if="rolePermissionsData.isEdit">
                <ShowTable
                  :tableData="IncludeUsersTableData"
                  :selections="selections"
                  :lableList="IncludeUsersLableList"
                  :talLength="IncludeUsersTalLength"
                  :pageSize="IncludeUsersPageSize"
                  :pageNum="IncludeUsersPageNum"
                  @getSortableFn="IncludeUsersGetSortableFn"
                ></ShowTable>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import ShowTable from "../components/table/show-table";
import Vmask from "../components/v-mask/v-mask";
// import PermissionsDetails from "./permissions-details"//角色权限详情
import {GetRoleList , AddRole , GetAllPermissions , Code , DeleteRole , RolePermissionModify , GetRolePermissions , IncludeUsers} from "@/axios/api.js"
export default {
  name: "",
  data() {
    return {
      IncludeUsersPageNum:1,//包含用户 当前页
      IncludeUsersPageSize:15,
      IncludeUsersTableData:[],
      IncludeUsersLableList:{//
        n1:'账号',
        n2:'角色',
        n3:'部门',
        n4:'姓名',
        n5:'邮箱',
        n6:'手机号码',
        n7:'电话号码',
        n8:'允许登录',
        n9:'是否禁用',
        n10:'加入排班',
      },
      IncludeUsersTalLength:0,
      maskTitle:'',
      maskData:{},
      showMask:false,
      maskWidth:'400px',
      rolePermissionsData:{},
      getPermissionsDetailsDate:{},
      selectSecondaryList:[],//次级列表
      lastSelectSecondary:[],//上次选择的次级列表
      lastSelectSecondaryData:'',//打钩了一级中的二级选项--确定打钩了
      showSelectSecondaryListBox:false,//是否展示二级权限选项
      permissionsSelectionList:[
        // {
        //   all:false,
        //   model:[],//'A@@1'
        //   list:[],//{label:'A',value:'1'},{label:'B',value:'2'}
        // },
        // {
        //   all:false,
        //   model:['C@@C1'],
        //   list:[{label:'C',value:'C1'},{label:'D',value:'D1'}]
        // },
        // {
        //   all:false,
        //   model:['D'],
        //   list:['C','D']
        // }
      ],//权限列表
      activeName: "first",
      selectionId: {}, //选中的id，可以编辑，删除
      showPermissionsDetails: false,
      tableData: [
        // {
        //   id: "1",
        //   n2: "n2"
        // }
      ],
      selections: false,
      lableList: {
        id: "ID",
        n1: "角色名称",
        n2: "角色编码"
      },
      talLength:0,
      pageSize: 15,
      pageNum: 1,
      contrastData:[],//对比的权限的数据
    };
  },
  props: [],
  created() {
   this.FnGetRoleList();//获取角色列表
  // this.FnGetAllPermissions()//所有权限
  },
  mounted() {},
  methods: {
    IncludeUsersGetSortableFn(e) {//包含用户表格发生的事件
      // console.log(e,'包含用户表格发生的事件')
      if(e.type=='pageSize') {
        this.IncludeUsersPageSize = e.content;
        this.FnIncludeUsers()
      }else if(e.type=='pageNum') {
        this.IncludeUsersPageNum = e.content;
        this.FnIncludeUsers()
      }
    },
    FnDeleteRole(e) {
      DeleteRole({
        roleId:e,
        _method:'delete'
      }).then(res=>{
        // console.log(res)
        if(res.code==Code) {
          this.$message.success("删除成功");
          this.FnGetRoleList()
          this.showMask = false;
          this.maskData = {};
          this.maskTitle = '';
          this.showPermissionsDetails = false;
        }
      })
    },
    FnMask(e) {
      if(e.type=='false') {
        this.showMask = false;
        this.maskData = {};
        this.maskTitle = '';
      }else if(e.type=='true') {
        if(e.content.delete){//删除角色
          this.FnDeleteRole(e.content.id)
        }
      }
    },
    FnGetAllPermissions(e) {//所有权限
      GetAllPermissions({
      }).then(res=>{
        if(res.code==Code) {
          this.permissionsSelectionList = [
            {
              all:false,
              id:'-1',
              title:'系统管理',
              model:[],//'A@@1'
              list:[],//{label:'A',value:'1'},{label:'B',value:'2'}
            }
          ]
          var list = res.obj.slice();
          for(var i=0;i<list.length;i++) {
            this.permissionsSelectionList[0].list.push({
              label:list[i].alias,
              value:list[i].permissionId,
              children:list[i].children&&list[i].children.length?list[i].children.slice():[]
              })
          }
          for(var i=0;i<list.length;i++) {
            var newPermissionList = [];
            if(list[i].children&&list[i].children.length){
              var permissionList = list[i].children.slice();
              for(var j=0;j<permissionList.length;j++) {
              newPermissionList.push({
                label:permissionList[j].alias,
                value:permissionList[j].permissionId,
              })
              }
            }
            this.permissionsSelectionList.push({
              id:list[i].permissionId,
              all:false,
              model:[],
              list:newPermissionList,
              title:list[i].alias
            })
            
          }
          this.contrastData = this.permissionsSelectionList.slice()
          if(e) {
            this.FnGetRolePermissions(this.selectionId)
          }else {
            this.showPermissionsDetails = true;
          }
        }
      })
    },
    FnAddRole(e,l) {//新增角色
      AddRole({
        roleName:e.roleName,
        roleCode:e.roleCode,
        auths:JSON.stringify(l)
      }).then(res=>{
        if(res.code==Code) {
          this.showPermissionsDetails = false;
          this.$message.success("新增角色成功")
          this.FnGetRoleList();//获取角色列表
        }
      })
    },
    FnGetRoleList () {
      GetRoleList({
        pageIndex:this.pageNum,
        pageSize:this.pageSize
      }).then(res=>{
        if(res.code==Code) {
          // console.log(res)
          this.talLength = res.obj.total;
          var list = res.obj.records.slice();
          this.tableData = [];
          for(var i=0;i<list.length;i++) {
            this.tableData.push({
              id: list[i].roleId,
              n1: list[i].roleName,
              n2: list[i].roleCode
            })
          }
        }
      })
    },
    FnSelectSecondaryAll (e,b) {//次级第二级-勾选全选
      console.log(e,'次级第二级-勾选全选--e')
      console.log(b,'次级第二级-勾选全选--b')
    },
    FnSelectSecondary (e,item) {//次级第二级-勾选了单个
      console.log(e,'次级第二级-勾选了单个--e')
      console.log(item,'次级第二级-勾选了单个--item')
    },
    FnRelationalTop(e) {//次级全选，关联顶级
      // console.log(e,'次级全选，关联顶级')
      // console.log(this.permissionsSelectionList,'permissionsSelectionList')
      if(e.id==-1) {//顶级
        if(e.all) {//顶级全选
          for(var i=0;i<this.permissionsSelectionList.length;i++) {
            if(i>0) {
              var modelList = this.permissionsSelectionList[i].list.slice();
              var newModelList = []
              for(var z=0;z<modelList.length;z++) {
                newModelList.push(modelList[z].label+'@@'+modelList[z].value)
              }
              this.permissionsSelectionList[i].model = newModelList
              this.permissionsSelectionList[i].all = true
            }
          }
        }else {
          for(var i=0;i<this.permissionsSelectionList.length;i++) {
            if(i>0) {
              this.permissionsSelectionList[i].model = []
              this.permissionsSelectionList[i].all = false
            }
          }
        }
      }else {
        if(e.all) {//次级全选
          var list = this.permissionsSelectionList[0].list;
          // console.log(list,'111111111')
          for(var i=0;i<list.length;i++) {
            if(list[i].value==e.id) {
              var indexOfNum = (this.permissionsSelectionList[0].model).indexOf(list[i].label+'@@'+list[i].value)
              // console.log(indexOfNum,'indexOfNum')
              if(indexOfNum==-1) {
                this.permissionsSelectionList[0].model.push(list[i].label+'@@'+list[i].value)
              }
            }
          }
          if(this.permissionsSelectionList[0].model.length==this.permissionsSelectionList[0].list.length) {
            this.permissionsSelectionList[0].all = true
          }else {
            this.permissionsSelectionList[0].all = false
          }
        }else {//次级不全选
          var list = this.permissionsSelectionList[0].list;
          for(var i=0;i<list.length;i++) {
            if(list[i].value==e.id) {
              var indexOfNum = (this.permissionsSelectionList[0].model).indexOf(list[i].label+'@@'+list[i].value)
              if(indexOfNum!=-1) {
                this.permissionsSelectionList[0].model.splice(indexOfNum,1)
              }
            }
          }
        }
      }
      
    },
    FnPermissionsSelectionAll (e,b) {//勾选全选
      this.FnRelationalTop(e)
      var arr = []
      var list = e.list.slice()
      if(b) {
        for(var i=0;i<list.length;i++) {
          arr.push(list[i].label+'@@'+list[i].value)
        }
      }
      e.model = b ? arr: [];
    },
    FnRelatedSubordinates(e) {//关联下级
        var newList = []
        var list = e.slice();
        for(var i=0;i<list.length;i++) {
            newList.push((list[i].split("@@")[1]))
        }
        for(var j=0;j<this.permissionsSelectionList.length;j++) {
            if(j>0) {
              this.permissionsSelectionList[j].all = false
              this.permissionsSelectionList[j].model=[]
            }
            
        }
        for(var i=0;i<newList.length;i++) {
          for(var j=0;j<this.permissionsSelectionList.length;j++) {
            if(newList[i]==this.permissionsSelectionList[j].id) {
              this.permissionsSelectionList[j].all = true
              var mobileList = this.permissionsSelectionList[j].list.slice();
              for(var z=0;z<mobileList.length;z++) {
                this.permissionsSelectionList[j].model.push(mobileList[z].label+'@@'+mobileList[z].value)
              }
            }
          }
        }
        // console.log(newList,'newList关联下级')
        // console.log(this.permissionsSelectionList,'permissionsSelectionList')
    },
    FnPermissionsSelection (e,item) {//勾选了单个
        // console.log(item,'item')
      // if(e.length>this.lastSelectSecondary.length) {//这次选中的长度大于上次的长度
      //   var list = e.slice();
      //   for(var i=0;i<list.length;i++) {
      //     if(list.length==1) {
      //         this.lastSelectSecondaryData = list[i]
      //           break
      //     }
      //     for(var j=0;j<this.lastSelectSecondary.length;j++) {
      //       if(list[i]==this.lastSelectSecondary[j]) {
      //         continue
      //       }else {
      //         if(i==(list.length-1)) {
      //           this.lastSelectSecondaryData = list[i]
      //           break
      //         }
      //       }
      //     }
      //   }
      // }
      this.lastSelectSecondary = e.slice();
      let checkedCount = e.length;
      item.all = checkedCount === item.list.length;
      if(item.id==-1) {//勾选了一级选项
        this.FnRelatedSubordinates(item.model)//关联下级
      }else {
        this.FnRelationalTop(item)
      }
      // console.log(e,'e')
    },
    handleClick(e,b) {
      if(this.activeName=='second') {//点击了包含用户
        this.IncludeUsersPageNum = 1;
        this.IncludeUsersPageSize = 15
        this.FnIncludeUsers(this.selectionId)
      }
    },
    FnIncludeUsers(e) {//点击了包含用户
      IncludeUsers({
        roleId:this.selectionId.id,
        pageIndex:this.IncludeUsersPageNum,
        pageSize:this.IncludeUsersPageSize,
      }).then(res=>{
        if(res.code==Code) {
          this.IncludeUsersTableData = [];
          var list = res.obj.records.slice();
          this.IncludeUsersTalLength = res.obj.total
          for(var i=0;i<list.length;i++) {
            this.IncludeUsersTableData.push({
                n1:list[i].userName,//'账号',
                n2:list[i].roleNames,//'角色',
                n3:list[i].regionName,//'部门',
                n4:list[i].realName,//'姓名',
                n5:list[i].email,//'邮箱',
                n6:list[i].mobile,//'手机号码',
                n7:list[i].extNumber,//'电话号码',
                n8:list[i].useableStatus?'是':'否',//'允许登录',
                n9:list[i].isStop?'是':'否',//'是否禁用',
                n10:list[i].enableWork?'是':'否',//'加入排班',
            })
          }
        }
        // console.log(res)
      })
    },
    FnDetails(e) {
      //冒泡得到详情发生的事件
      // console.log(e, "冒泡得到详情发生的事件");
    },
    FnSave() {//保存按钮
        if(!this.rolePermissionsData.roleCode||!this.rolePermissionsData.roleName||this.rolePermissionsData.roleCode===''||this.rolePermissionsData.roleName===''){
          this.$message.error("参数不能为空");
          return
        }
        var list = [];
        var permissionsSelectionList = this.permissionsSelectionList.slice();
        for(var i=0;i<permissionsSelectionList.length;i++) {
          if(permissionsSelectionList[i].model.length) {
            if(i>0&&permissionsSelectionList[i].model.length==permissionsSelectionList[i].list.length){
              list.push(permissionsSelectionList[i].id*1)
            }
            var model = permissionsSelectionList[i].model.slice();
            for(var j=0;j<model.length;j++) {
              var st = model[j].split("@@")
              list.push(st[1]*1)
            }
          }
        }
        var removalList = [];
        var obj = {}
        for(var i=0;i<list.length;i++) {
          if(!obj[list[i]]) {
            removalList.push(list[i]);
            obj[list[i]] = 1
          }
        }
        this.FnAddRole(this.rolePermissionsData,removalList)
    },
    FnGetRolePermissions(e) {//获取当前角色权限
      var that = this;
      GetRolePermissions({
        roleId:e.id
      }).then(res=>{
        var list = res.obj.slice();//已有权限
        var permissionsSelectionList = that.contrastData.slice();//需要对比的权限
        for(var i=0;i<permissionsSelectionList.length;i++) {
          var itemList = permissionsSelectionList[i].list.slice();
          list.forEach((v)=>{
            itemList.forEach((n,nIndex)=>{
              if(v.permissionId==n.value) {
                // console.log(n,'找到啦')
                // console.log(permissionsSelectionList[i],'找到顶级啦')
                if(i>0) {
                  permissionsSelectionList[i].model.push(n.label+'@@'+n.value)
                  if(permissionsSelectionList[i].model.length==permissionsSelectionList[i].list.length) {
                    permissionsSelectionList[i].all = true
                  }
                }
              }
          })
          })
        }

        permissionsSelectionList.forEach((v,i)=>{
          if(i>0) {
            if(v.all) {//次级全选
              permissionsSelectionList[0].list.forEach((n,nIndex)=>{
                if(n.value==v.id) {
                  permissionsSelectionList[0].model.push(n.label+'@@'+n.value);
                  if(permissionsSelectionList[0].model.length==permissionsSelectionList[0].list.length) {
                    permissionsSelectionList[0].all = true
                  }
                }
              })
            }
          }
        })
        that.permissionsSelectionList = permissionsSelectionList;
        this.showPermissionsDetails = true;
      })
    },
    FnRolePermissionModify() {//修改角色权限
      if(!this.rolePermissionsData.roleCode||!this.rolePermissionsData.roleName||this.rolePermissionsData.roleCode===''||this.rolePermissionsData.roleName===''){
          this.$message.error("参数不能为空");
          return
        }
        var list = [];
        var permissionsSelectionList = this.permissionsSelectionList.slice();
        for(var i=0;i<permissionsSelectionList.length;i++) {
          if(permissionsSelectionList[i].model.length) {
            if(i>0&&permissionsSelectionList[i].model.length==permissionsSelectionList[i].list.length){
              list.push(permissionsSelectionList[i].id*1)
            }
            var model = permissionsSelectionList[i].model.slice();
            for(var j=0;j<model.length;j++) {
              var st = model[j].split("@@")
              list.push(st[1]*1)
            }
          }
        }
        var removalList = [];
        var obj = {}
        for(var i=0;i<list.length;i++) {//去重
          if(!obj[list[i]]) {
            removalList.push(list[i]);
            obj[list[i]] = 1
          }
        }
      RolePermissionModify({
        roleId:this.rolePermissionsData.roleId,
        roleCode:this.rolePermissionsData.roleCode,
        roleName:this.rolePermissionsData.roleName,
        auths:JSON.stringify(removalList)
      }).then(res=>{
        // console.log(res)
        if(res.code==Code) {
          this.FnGetRoleList()
          this.$message.success("修改成功");
          this.showPermissionsDetails = false;
        }
      })
    },
    FnRoleEvent(e) {
      this.showPermissionsDetails = false;
      //角色 新增，编辑，删除
      if (e.type == "addRole") {
        this.rolePermissionsData = {}
        this.FnGetAllPermissions()//获取所有权限
        this.selectionId.id = false; //新增就取消选定的id
      } else if (e.type == "editRole") {
        //编辑
        if (!this.selectionId.id) {
          this.$message.error("请选择id");
          return;
        }
        this.activeName = 'first'
        this.FnGetAllPermissions(1)
        this.rolePermissionsData = {
          roleCode:this.selectionId.roleCode,
          roleName:this.selectionId.roleName,
          roleId:this.selectionId.id,
          isEdit:true
        }
      } else if (e.type == "deleteRole") {
        if (!this.selectionId.id) {
          this.$message.error("请选择id");
          return;
        }
        this.showMask = true;
        this.maskTitle = "删除";
        this.maskData = {
          id:this.selectionId.id,
          delete: true,
          trueOrFalse: true,
          defaultTitleBox:true,
          defaultTitle:'请问确定删除吗',
        };
      }
    },
    getSortableFn(e) {
      // console.log(e, "表发生事件");
      if (e.type == "selectionRow") {
        //单击行
        this.selectionId = {
          id: e.content.id,
          roleName: e.content.n1,
          roleCode: e.content.n2,
        }
      }else if(e.type=="pageSize") {
        this.pageSize = e.content
        this.FnGetRoleList()
      }else if(e.type=="pageNum") {
        this.pageNum = e.content
        this.FnGetRoleList()
      }
    },
    FnShowSelectSecondaryListBox(e) {//根据次级id展示二级列表
        if(!e) {
          return
        }
        var id = e.substr(e.indexOf('@@')+2); 
        var list = this.permissionsSelectionList;
        for(var i=0;i<list.length;i++) {
          if(list[i].id==id) {
            list[i].all=true;
            if(list[i].list&&list[i].list.length) {
              var modelList = list[i].list.slice();
              for(var j=0;j<modelList.length;j++) {
                list[i].model.push(modelList[j].label+'@@'+modelList[j].value)
              }
            }
          }
        }
        // console.log(list,'list改后')
        // console.log(this.contrastData,'contrastData')
    }
  },
  components: {
    ShowTable,
    Vmask
    // PermissionsDetails
  },
  computed: {},
  watch: {
    'lastSelectSecondaryData':{//拿到了次级id
      handler:function(n,o) {
        this.FnShowSelectSecondaryListBox(n)
      },
      deep:true
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang='scss' scoped>
.hwx-role-permissions {
  padding-left: 15px;
  .role-permissions-content {
    .role-permissions-content-left {
      width: 475px;
    }
  }
  .hsx-permissions-details {
    overflow: hidden;
    padding-left: 15px;
    .condition {
      padding-top: 15px;
    }
    .h-permissions-details-tabs {
      margin-left: 1px;
      .permissions-select {
        table {
          width: 100%;
          border-collapse: collapse;
          text-align: center;
          line-height: 30px;
          padding: 0;
          td,
          th {
            border: 1px solid #dcdfe6;
          }
          tr {
            td:nth-child(1) {
              width: 80px;
            }
            td:nth-child(2) {
              width: 80px;
            }
            // td:nth-child(3) {
            //   width: 40px;
            // }
          }
        }
      }
    }
  }
}
</style>
